/**
 * Copyright (C), 2018 store
 * Encoding: UTF-8
 * Date: 20-3-24 下午1:46
 * History:
 */
package com.swak.frame.eventbus;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.swak.frame.logger.SwakLoggerFactory;

/**
 * EventBusAdapter.java
 *
 * @author ColleyMa
 * @version 20-3-24 下午1:46
 */
public class EventBusAdapter extends AsyncEventBus implements InitializingBean {
    private Map<String, Byte> listeners = Maps.newConcurrentMap();
    private Logger logger = SwakLoggerFactory.getLogger(getClass()); // 日志记录
    private List<EventListener<?>> eventBusListener = Lists.newArrayList();

    public EventBusAdapter(Executor executor) {
        super("marsAsyncEvent", executor);
    }

    public void setEventBusListener(List<EventListener<?>> eventBusListener) {
        this.eventBusListener = eventBusListener;
    }

    /**
     * 添加监听
     *
     * @param listener
     *
     * @return
     */
    public EventBusAdapter addEvent(EventListener<?> listener) {
        if (listener == null) {
            return this;
        }

        String clzName = listener.getClass().getName();
        logger.warn("addListener listener: >>>>>>>>> {} ", clzName);

        if (listeners.get(clzName) == null) {
            synchronized (listeners) {
                if (listeners.get(clzName) == null) {
                    this.register(listener);
                    listeners.putIfAbsent(clzName, (byte) 1);
                }
            }
        }

        return this;
    }

    /**
     * 添加监听并且post event
     *
     * @param listener
     * @param event
     *
     * @return
     */
    public EventBusAdapter addListener(EventListener<?> listener, Object event) {
        this.addEvent(listener);

        if (event != null) {
            this.post(event);
        }

        return this;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (CollectionUtils.isEmpty(eventBusListener)) {
            eventBusListener.add(new EventSubscriber());
        }
        for (EventListener<?> eventAbstract : eventBusListener) {
            Byte event = listeners.putIfAbsent(eventAbstract.getClass().getName(), (byte) 1);
            // 不存在就注册
            if (event == null) {
                logger.warn("EventBusAdapter register {} >>>>>>>>>>>>>>>>>>>>>> ",
                    eventAbstract.getClass().getName());
                this.register(eventAbstract);
            }
        }
    }
}
